from typing import Any, Dict
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from jwt import ExpiredSignatureError
from rest_framework.authentication import BaseAuthentication

from apps.libs.arch_jwt import TokenManager

from rest_framework.exceptions import AuthenticationFailed, APIException
from rest_framework_simplejwt.tokens import RefreshToken


class JWTLoginAuth(BaseAuthentication):
    def authenticate(self, request):
        from apps.models import User
        token = request.META.get("HTTP_AUTHORIZATION", None)
        if token:
            try:
                payload = TokenManager.get_payload(token)
                user = User.objects.get(pk=payload.get('user_id'))
                return user, token
            except ExpiredSignatureError:
                raise APIException('token过期或者用户未找到')
        else:
            raise AuthenticationFailed('没有携带token信息')


class JWT(TokenObtainPairSerializer):
    def validate(self, attrs: Dict[str, Any]) -> Dict[str, str]:
        # {'refresh': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcxODI1MTE1MywiaWF0IjoxNzE3NjQ2MzUzLCJqdGkiOiIzMWI1ZjNjMjk5MTc0OTAwYTE5YWU5OGQ3NjlhODEyYiIsInVzZXJfaWQiOjN9.twxhiFC2Y_04fbh0W2aZ0huVVGZKQebHsFwo_CnOeKQ', 
        # 'access': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzE3NjQ2NjUzLCJpYXQiOjE3MTc2NDYzNTMsImp0aSI6ImQxNjhkZmIxZWIxMTQyNjM5MTM2YmIxMjc2N2ZlN2MwIiwidXNlcl9pZCI6M30.huN9SGwBVtFO7FaJpntrmYnTVyYdwQwsVnqS4ae2TyU'}
       dic = super().validate(attrs)
       return {
           "code": 100,
           "msg": "登录成功",
           "username": self.user.username or '未登录',
           "token": dic['access']
       }
        
